import { HashRouter, Routes, Route } from "react-router-dom";
import Login from "../pages/login/index";
import Layoutc from "../pages/layout/index";
import { connect } from "react-redux";
// import Home from "../pages/home/index";
import NotFound from "../pages/notFound";
// import UserList from "../pages/userList";
// import MemberList from "../pages/memberList/index";
// import CommodityManage from "../../src/pages/commoditymanage/index";
// import Order from "../../src/pages/orderMement/index.jsx";
// import RoleSet from "../../src/pages/roleSet/index";
import { lazy, Suspense } from "react";
const Home = lazy(() => import("../pages/home"));
const UserList = lazy(() => import("../pages/userList"));
const MemberList = lazy(() => import("../pages/memberList"));
const CommodityManage = lazy(() => import("../pages/commoditymanage"));
const Order = lazy(() => import("../pages/orderMement"));
const RoleSet = lazy(() => import("../pages/roleSet"));

// lazy 可以分片打包模块。
// 默认react打包会把所有文件的js打包到一个文件，这样访问项目第一次加载会很慢，为了解决该问题，可以用分片，把每个js文件单独打包，访问页面的才加载js，这样页面能很快的渲染出来，提高网站的访问速
function App({ auth }) {
  console.log(auth);
  // 组件和路由的对应关系对象
  const COM_MAP = {
    "/": Home,
    "/userlist": UserList,
    "/memberlist": MemberList,
    "/commodityManage": CommodityManage,
    "/order": Order,
    "/roleset": RoleSet,
  };
  function getComByPath(path) {
    const Com = COM_MAP[path];
    // 分片加载的组件由于需要加载时间，需要放在Suspense组件里面，Suspense的fallback属性设置当组件没有加载完成显示的内容
    return (
      <Suspense fallback={<div>loading....</div>}>
        <Com />
      </Suspense>
    );
  }
  return (
    <HashRouter>
      <Routes>
        <Route path="/login" element={<Login />}></Route>
        <Route path="/" element={<Layoutc />}>
          {/* 遍历角色配置信息将路由动态的渲染出来 */}
          {Object.keys(auth).map(
            (item) =>
              auth[item].view.value && (
                <Route
                  key={item}
                  path={item.replace("/", "")}
                  element={getComByPath(item)}
                ></Route>
              )
          )}
        </Route>
        {/* <Route path="" element={<Home />}></Route>
          <Route path="userlist" element={<UserList />}></Route>
          <Route path="memberlist" element={<MemberList />}></Route>
          <Route path="commodityManage" element={<CommodityManage />}></Route>
          <Route path="order" element={<Order />}></Route>
          <Route path="roleset" element={<RoleSet />}>   </Route> */}
        <Route path="*" element={<NotFound />}></Route>
      </Routes>
    </HashRouter>
  );
}
export default connect((state) => {
  let auth = {};
  if (state.user?.roleAuthority) {
    auth = JSON.parse(state.user.roleAuthority);
  }
  return { auth };
})(App);
